﻿using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ZhCun.Utils;

namespace ZhCun.WebUtils
{
    public class GlobalExceptionsFilter : Attribute, IExceptionFilter
    {
        private readonly IWebHostEnvironment _Environment;

        public GlobalExceptionsFilter(IWebHostEnvironment environment)
        {
            this._Environment = environment;
        }

        public void OnException(ExceptionContext context)
        {
            Exception exception = context.Exception;
            //string error = string.Empty;

            //void ReadException(Exception ex)
            //{
            //    error += string.Format("{0} | {1} | {2}", ex.Message, ex.StackTrace, ex.InnerException);
            //    if (ex.InnerException != null)
            //    {
            //        ReadException(ex.InnerException);
            //    }
            //}

            LogHelper.LogObj.Error("服务器发生异常", exception);

            //ReadException(context.Exception);

            ContentResult result = new ContentResult
            {
                StatusCode = 500,
                ContentType = "text/json;charset=utf-8;"
            };

            result.Content = "服务器发生异常，请联系管理员";

            //result.Content = "抱歉，出错了";

            //var evName = _Environment.EnvironmentName;
            //if (_Environment.IsDevelopment())
            //{
            //    var json = new { message = exception.Message, detail = error };
            //    result.Content = json.ToJson();
            //}
            //else
            //{
            //    result.Content = "抱歉，出错了";
            //}
            context.Result = result;
            context.ExceptionHandled = true;
        }
    }

}
